//
//  RemoteAirViewController.m
//  OST
//
//  Created by mac on 13-7-11.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "RemoteAirViewController.h"
#import "CommonData.h"
#import "wis.h"
#import "Utitlity.h"
#import "MMProgressHUD.h"
#import "PersistableInfo.h"

#define INTERVAL_SECOND_SEND_TEMP_CMD 2.0f

@interface RemoteAirViewController ()
{
    NSTimer *_timerDetectIntervalToSetTempCMDSend;
    NSMutableArray *jsondataArray;
    NSArray *allAirModeArray;
    NSArray *allFanModeArray;
    NSMutableArray *airModeArray;
    NSMutableArray *fanModeArray;
    int airValue;
    int fanValue;
    NSString *ipUrl;
    NSInteger pickerIndex;
    NSInteger IRIndex;
    NSArray *tempArray;
    NSString *airM;
    NSUserDefaults *userDefaults;
    
    NSMutableArray *IRArray;
    NSTimer *timer;
    
    UIPickerView *ios8Picker;
    BOOL isSetted;
    
    int windInt;
}
@property (nonatomic, strong) NSString *zIDStr;
@property (weak, nonatomic) IBOutlet UIButton *IRBtn;
@property (weak, nonatomic) IBOutlet UIView *adjustView;

@end

@implementation RemoteAirViewController
@synthesize Rdata;
@synthesize btn_air_mode,btn_cur_temp,btn_fan_mode,btn_power,btn_set_temp,btn_switcher;
@synthesize actionPicker;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    airModeArray = [[NSMutableArray alloc] init];
    fanModeArray = [[NSMutableArray alloc] init];
    CGRect rx = [ UIScreen mainScreen ].bounds;
    
    if (rx.size.height <500)
    {
        self.adjustView.frame = CGRectMake(0, -60, self.adjustView.frame.size.width,self.adjustView.frame.size.height );
    }
    
    [btn_power setImage:[UIImage imageNamed:@"air_on"] forState:UIControlStateSelected];
    [btn_power setImage:[UIImage imageNamed:@"air_off"] forState:UIControlStateNormal];

    //_timerDetectIntervalToSetTempCMDSend = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(<#selector#>) userInfo:nil repeats:YES];
    
    [self intitalView];
    
    jsondataArray = [[NSMutableArray alloc] init];

    allAirModeArray= [NSArray arrayWithObjects:
                      [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"value",@"Off",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"value",@"Heat",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"value",@"Cool",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"value",@"Auto",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"4",@"value",@"Aux Heat",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"5",@"value",@"Resume",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"value",@"Fan Only",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"7",@"value",@"Furnace",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"value",@"Dry Air",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"9",@"value",@"Moist Air",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"10",@"value",@"Auto Changeover",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"11",@"value",@"Heat Econ",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"12",@"value",@"Cool Econ",@"label", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"13",@"value",@"Away",@"label", nil],
                      nil];
    
    allFanModeArray = [NSArray arrayWithObjects:
                       [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"value",@"Auto Low",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"value",@"On Low",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"value",@"Auto High",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"value",@"On High",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"4",@"value",@"Auto Medium",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"5",@"value",@"On Medium",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"value",@"Circulate",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"7",@"value",@"Humidity Circulation",@"label", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"value",@"Unknown",@"label", nil],
                       nil];
    
    pickerView_air = [[UIPickerView alloc]initWithFrame:CGRectZero];
	pickerView_air.dataSource = self;
	pickerView_air.delegate = self;
    pickerView_air.tag = 100;
	pickerView_air.showsSelectionIndicator = YES;
    
    pickerView_fan = [[UIPickerView alloc]initWithFrame:CGRectZero];
	pickerView_fan.dataSource = self;
	pickerView_fan.delegate = self;
    pickerView_fan.tag = 200;
	pickerView_fan.showsSelectionIndicator = YES;
    
    pickerTemp = [[UIPickerView alloc] initWithFrame:CGRectZero];
    pickerTemp.dataSource = self;
    pickerTemp.delegate = self;
    pickerTemp.tag = 300;
    pickerTemp.showsSelectionIndicator = YES;
    
    IRPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
    IRPicker.dataSource = self;
    IRPicker.delegate = self;
    IRPicker.tag = 400;
    IRPicker.showsSelectionIndicator = YES;
    
    [btn_set_temp addTarget:self action:@selector(tempSet:) forControlEvents:UIControlEventTouchUpInside];
    [self.IRBtn addTarget:self action:@selector(irCode:) forControlEvents:UIControlEventTouchUpInside];
    
    //[self loadData];
    self.zIDStr = [Rdata objectForKey:@"ZID"];
    [self loadDataSource];
    timer=[NSTimer scheduledTimerWithTimeInterval:120
                                           target:self
                                         selector:@selector(loadHttpData)
                                         userInfo:nil
                                          repeats:YES];
}
- (void)intitalView
{
    userDefaults = [NSUserDefaults standardUserDefaults];
    [btn_set_temp setTitle:[userDefaults objectForKey:@"set"] forState:UIControlStateNormal];
    [btn_cur_temp setTitle:[userDefaults objectForKey:@"cur"] forState:UIControlStateNormal];
    [btn_air_mode setTitle:[userDefaults objectForKey:@"air"] forState:UIControlStateNormal];
    [btn_fan_mode setTitle:[userDefaults objectForKey:@"fan"] forState:UIControlStateNormal];
    [self.IRBtn setTitle:[userDefaults objectForKey:@"ir"] forState:UIControlStateNormal];
    
    if (![[userDefaults objectForKey:@"air"] isEqualToString:@"Off"])
    {
        self.btn_power.selected = YES;
    }
    
    if ([userDefaults objectForKey:@"airMode"])
    {
        airModeArray = [[userDefaults objectForKey:@"airMode"] mutableCopy];
    }
    
    if ([userDefaults objectForKey:@"fanMode"])
    {
        fanModeArray = [[userDefaults objectForKey:@"fanMode"] mutableCopy];
    }
    
    if ([userDefaults objectForKey:@"windInt"])
    {
        if ([[userDefaults objectForKey:@"windInt"] intValue] == 0)
        {
            btn_switcher.selected = NO;
        }
        else
        {
            btn_switcher.selected = YES;
        }
    }

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    isSetted = YES;
    [timer invalidate];
    timer = nil;
}

#pragma mark -  GetCmdData

- (void)loadDataSource
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        [self getAirAllMode];
        [self getAirCurrentStatus];
        [self getIRCode];
        [self getCurrentTemp];
        [self getSettedTempData];
        [self getFanAllMode];
        [self getFanCurrentStatus];
        [self getWindStatus];
    }
    else
    {
        [self getAirCurrentStatus];
    }
}

- (void)loadHttpData
{
    if (ipUrl)
    {
        [self getCurrentTemp];
    }
}

- (WisDevThermostatGetCmd)getWisDevThermostatGetCmdData:(int)get_index
{
    WisDevThermostatGetCmd cmd;
    memset(&cmd, 0, sizeof(WisDevThermostatGetCmd));
    strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String]);
    strcpy(cmd.did, [self.zIDStr UTF8String]);
    cmd.get_index = get_index;
    return cmd;
}


//get air/fan支持模式
- (void)getAirAllMode
{
    ipUrl = [Utitlity judgeipUrl];
    
    if (ipUrl)
    {
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,1];
        
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
             NSLog(@"getAirAllMode:%@",responseObject);
            
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            if(![responseObject[@"state"] isKindOfClass:[NSNumber class]])
            {
                if([responseObject[@"state"] isEqualToString:@"Success"])
                {
                    NSDictionary *tempAirDic = responseObject[@"data"];
                    if(tempAirDic == nil) return;
                    NSString * currentAirNum = tempAirDic[@"Value"];
                    NSArray *array = [[NSArray alloc] init];
                    array = [currentAirNum componentsSeparatedByString:@","];
                    [airModeArray removeAllObjects];
                    for (int i = 0 ;i < [array count]; i++)
                    {
                        NSDictionary *dic = [allAirModeArray objectAtIndex:i];
                        [airModeArray addObject:[dic objectForKey:@"label"]];
                    }
                    if([airModeArray count] > 0)
                    {
                        userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:airModeArray forKey:@"airMode"];
                    }
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self getFanAllMode];
//                    });
                }
            }
//            else
//            {
//                [self getAirAllMode];
//            }
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];

    }
    else
    {
        
        //tcp
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:1];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_GET cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata)
         {
             if (!jsondata || ![jsondata isKindOfClass:[NSDictionary class]]) return;
             
             NSLog(@"getAirAllMode-tcp:%@",jsondata);
             
             if(![jsondata[@"state"] isKindOfClass:[NSNumber class]])
             {
                 
                 if([jsondata[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *tempAirDic = jsondata[@"data"];
                     if(tempAirDic == nil) return;
                     
                     NSString * currentAirNum = tempAirDic[@"Value"];
                     NSString * airNum = [NSString stringWithFormat:@"%@",currentAirNum];
                     NSArray * array = [[NSArray alloc] init];
                     if (airNum.length > 1)
                     {
                         [airModeArray removeAllObjects];
                          array = [airNum componentsSeparatedByString:@","];
                     }
                     else
                     {
                         array = airModeArray;
                     }
//                     NSArray * array = [currentAirNum componentsSeparatedByString:@","];
                     for (int i = 0 ;i < [array count]; i++)
                     {
                         NSDictionary *dic = [allAirModeArray objectAtIndex:i];
                         [airModeArray addObject:[dic objectForKey:@"label"]];
                     }
                     if([airModeArray count] > 0)
                     {
                         userDefaults = [NSUserDefaults standardUserDefaults];
                         [userDefaults setObject:airModeArray forKey:@"airMode"];
                     }
                     
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [self getFanAllMode];
                     });
                 }
             }
             else
             {
             }
         }];
    }
}

- (void)getFanAllMode
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        fanModeArray = [[NSMutableArray alloc] init];
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,2];
        
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSLog(@"getFanAllMode:%@",responseObject);
             
             if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             
             if(![responseObject[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([responseObject[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *tempFanDic = responseObject[@"data"];
                     NSString * currentFanNum = tempFanDic[@"Value"];
                     NSArray * array = [currentFanNum componentsSeparatedByString:@","];
                     [fanModeArray removeAllObjects];
                     
                     for (int i = 0 ;i < [array count]; i++)
                     {
                         NSDictionary *dic = [allFanModeArray objectAtIndex:i];
                         [fanModeArray addObject:[dic objectForKey:@"label"]];
                     }
                     
                     if ([fanModeArray count] > 0) {
                         userDefaults = [NSUserDefaults standardUserDefaults];
                         [userDefaults setObject:fanModeArray forKey:@"fanMode"];
                     }
                     
                 }
//                 else
//                 {
//                     [self getFanAllMode];
//                 }
//                 dispatch_async(dispatch_get_main_queue(), ^{
//                    [self getFanCurrentStatus];
//                 });
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
        //tcp
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:2];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_GET  cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata)
         {
             
             NSLog(@"getFanAllMode:%@",jsondata);
             
             if (!jsondata || ![jsondata isKindOfClass:[NSDictionary class]]) return;
             
             if(![jsondata[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([jsondata[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *tempFanDic = jsondata[@"data"];
                     NSString * currentFanNum = tempFanDic[@"Value"];
                     NSString *fanStr = [NSString stringWithFormat:@"%@",currentFanNum];
                     NSArray *array = [[NSArray alloc] init];
                     if (fanStr.length > 1)
                     {
                         [fanModeArray removeAllObjects];
                         array = [fanStr componentsSeparatedByString:@","];
                     }
                     else
                     {
                         array = fanModeArray;
                     }
                     for (int i = 0 ;i < [array count]; i++)
                     {
                         NSDictionary *dic = [allFanModeArray objectAtIndex:i];
                         [fanModeArray addObject:[dic objectForKey:@"label"]];
                     }
                     
                     if ([fanModeArray count] > 0) {
                         userDefaults = [NSUserDefaults standardUserDefaults];
                         [userDefaults setObject:fanModeArray forKey:@"fanMode"];
                     }
                 }
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [self getFanCurrentStatus];
                 });
             }
             else
             {
//                 [self getFanAllMode];
             }
         }];
    }
}


//get air and fan current status
- (void) getAirCurrentStatus
{
    //air 当前状态
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,3];
        
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
              NSLog(@"getAirCurrentStatus:%@",responseObject);
             
             if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             
             if (![responseObject[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([responseObject[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *airDataDic = responseObject[@"data"];
                     airValue = [airDataDic[@"Value"] intValue];
                     
                     if (airValue <= 0)
                     {
                         mPower = 0;
                         btn_power.selected = NO;       //power btn
                     }
                     else if (airValue > 0)
                     {
                         mPower = 1;
                         btn_power.selected = YES;
                     }
                     
                     NSDictionary *airValueDic = [allAirModeArray objectAtIndex:airValue];
                     [btn_air_mode setTitle:airValueDic[@"label"] forState:UIControlStateNormal];
                     userDefaults = [NSUserDefaults standardUserDefaults];
                     [userDefaults setObject:airValueDic[@"label"] forKey:@"air"];
                 }
             }
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"error:%@",error);
         }];

    }
    else
    {
        NSLog(@"%@",[GlobalService sharedInstance].curOperationDeviceUUID);
        //tcp
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:3];
        
        [[CMDDataProcessor sharedInstance]sendCMDId:WIS_CMD_V2_THERMOSTAT_GET cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata)
         {
             
              NSLog(@"getAirCurrentStatus-tcp :%@",jsondata);
             
             if (!jsondata || ![jsondata isKindOfClass:[NSDictionary class]]) return;
             
             if (![jsondata[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([jsondata[@"state"] isEqualToString:@"Success"])
                 {
                     if ([jsondata[@"data"] isKindOfClass:[NSArray class]])
                     {
                         return;
                     }
                     NSDictionary *airDataDic = jsondata[@"data"];
                     airValue = [airDataDic[@"Value"] intValue];
                     NSDictionary *airValueDic = [allAirModeArray objectAtIndex:airValue];
                     [btn_air_mode setTitle:airValueDic[@"label"] forState:UIControlStateNormal];
                     userDefaults = [NSUserDefaults standardUserDefaults];
                     [userDefaults setObject:airValueDic[@"label"] forKey:@"air"];
                     
                     if (airValue <= 0)
                     {
                         mPower = 0;
                         btn_power.selected = NO;       //power btn
                     }else if (airValue > 0)
                     {
                         mPower = 1;
                         btn_power.selected = YES;
                     }
                 }
                 
                 dispatch_async(dispatch_get_current_queue(), ^{
                     [self getAirAllMode];
                 });
             }
         }];
    }
}

- (void)getFanCurrentStatus
{
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,4];
        
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
              NSLog(@"getFanCurrentStatus:%@",responseObject);
             
             if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             
             if (![responseObject[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([responseObject[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *fanDataDic = responseObject[@"data"];
                     fanValue = [fanDataDic[@"Value"] intValue];
                     NSDictionary *fanValueDic = [allFanModeArray objectAtIndex:fanValue];
                     NSLog(@"fanValueDic:%@",fanValueDic);
                     [btn_fan_mode setTitle:fanValueDic[@"label"] forState:UIControlStateNormal];
                     btn_fan_mode.titleLabel.text = fanValueDic[@"label"];
                     userDefaults = [NSUserDefaults standardUserDefaults];
                     [userDefaults setObject:fanValueDic[@"label"] forKey:@"fan"];
                 }
                 
//                 dispatch_async(dispatch_get_main_queue(), ^{
//                     [self getCurrentTemp];
//                 });
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
        //tcp
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:4];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_GET cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata) {
            
            NSLog(@"getFanCurrentStatus:%@",jsondata);
            
            if (!jsondata || ![jsondata isKindOfClass:[NSDictionary class]]) return;
            
            if (![jsondata[@"state"] isKindOfClass:[NSNumber class]])
            {
                if ([jsondata[@"state"] isEqualToString:@"Success"])
                {
                    NSDictionary *fanDataDic = jsondata[@"data"];
                    fanValue = [fanDataDic[@"Value"] intValue];
                    NSDictionary *fanValueDic = [allFanModeArray objectAtIndex:fanValue];
                    NSLog(@"fanValueDic:%@",fanValueDic);
                    [btn_fan_mode setTitle:fanValueDic[@"label"] forState:UIControlStateNormal];
                    btn_fan_mode.titleLabel.text = fanValueDic[@"label"];
                    
                    //baocun
                    userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:fanValueDic[@"label"] forKey:@"fan"];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self getCurrentTemp];
                });
            }
        }];
    }
}

//get 温度
- (void)getSettedTempData
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,5];
        
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
              NSLog(@"getSettedTempData:%@",responseObject);
             
             if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             
             if (![responseObject[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([responseObject[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *settedTempDic = responseObject[@"data"];
                     NSString *settedTemperature = [NSString stringWithFormat:@"%@",settedTempDic[@"Value"]];
                     temp  = [settedTemperature intValue];
                     //    NSString *settedUnit = settedTempDic[@"Unit"];
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [btn_set_temp setTitle:settedTemperature forState:UIControlStateNormal];
                         btn_set_temp.titleLabel.text = settedTemperature;
                         
                         userDefaults = [NSUserDefaults standardUserDefaults];
                         [userDefaults setObject:settedTemperature forKey:@"set"];
//                         [self getWindStatus];
                     });
                 }
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
        //tcp
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:5];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_GET cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata){
            
            NSLog(@"getSettedTempData-tcp:%@",jsondata);
            
            if (![jsondata[@"state"] isKindOfClass:[NSNumber class]])
            {
                if ([jsondata[@"state"] isEqualToString:@"Success"])
                {
                    isSetted = YES;
                    NSDictionary *settedTempDic = jsondata[@"data"];
                    NSString *settedTemperature = [NSString stringWithFormat:@"%@",settedTempDic[@"Value"]];
                    temp  = [settedTemperature intValue];
                    //    NSString *settedUnit = settedTempDic[@"Unit"];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [btn_set_temp setTitle:settedTemperature forState:UIControlStateNormal];
                        btn_set_temp.titleLabel.text = settedTemperature;
                        userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:settedTemperature forKey:@"set"];
                        [self getWindStatus];
                    });
                }
//                else
//                {
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (!isSetted)
//                        {
//                            [self getSettedTempData];
//                        }
//                        
//                    });
//                }
            }
        }];
    }
}

- (void)getCurrentTemp
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,6];
        
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
              NSLog(@"getCurrentTemp:%@",responseObject);
             
             if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             
             if (![responseObject[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([responseObject[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *currentTempDic = responseObject[@"data"];
                     
                     NSString *currentTemperature =[NSString stringWithFormat:@"%@",currentTempDic[@"Value"]];

                     //    NSString *currentUnit = currentTempDic[@"Unit"];
                     
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [btn_cur_temp setTitle:currentTemperature forState:UIControlStateNormal];
                         btn_cur_temp.titleLabel.textAlignment = UITextAlignmentCenter;
                         btn_cur_temp.titleLabel.text = currentTemperature;
                         
                         userDefaults = [NSUserDefaults standardUserDefaults];
                         [userDefaults setObject:currentTemperature forKey:@"cur"];
//                        [self getSettedTempData];
                     });
                 }
//                 else
//                 {
//                     [self getCurrentTemp];
//                 }
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:6];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_GET cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata){
            
             NSLog(@"getCurrentTemp:%@",jsondata);
            
            if (!jsondata || ![jsondata isKindOfClass:[NSDictionary class]]) return;
            
            if (![jsondata[@"state"] isKindOfClass:[NSNumber class]])
            {
                if ([jsondata[@"state"] isEqualToString:@"Success"])
                {
                    NSDictionary *currentTempDic = jsondata[@"data"];
                    NSString *currentTemperature =[NSString stringWithFormat:@"%@",currentTempDic[@"Value"]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [btn_cur_temp setTitle:currentTemperature forState:UIControlStateNormal];
                        btn_cur_temp.titleLabel.textAlignment = UITextAlignmentCenter;
                        btn_cur_temp.titleLabel.text = currentTemperature;
                        userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:currentTemperature forKey:@"cur"];
                        [self getSettedTempData];
                    });
                }
//                else
//                {
//                    [self getCurrentTemp];
//                }
            }
        }];
    }
}

//get 扫风是否打开
- (void)getWindStatus
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,7];
        
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
              NSLog(@"getWindStatus:%@",responseObject);
             if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             
             if(![responseObject[@"state"] isKindOfClass:[NSNumber class]])
             {
                 if ([responseObject[@"state"] isEqualToString:@"Success"])
                 {
                     NSInteger windirValue = [responseObject[@"state"] intValue];
                     btn_switcher.selected = !(windirValue==0);
                     
                     //保存风向状态
                     if (windirValue == 0)
                     {
                         btn_switcher.selected = NO;
                         windInt = 0;
                     }
                     else
                     {
                         btn_switcher.selected = YES;
                         windInt = 1;
                     }
                 }
                 NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                 [user setObject:[NSString stringWithFormat:@"%d",windInt] forKey:@"windInt"];
//                 else
//                 {
//                     [self getWindStatus];
//                 }
             }
//             dispatch_async(dispatch_get_main_queue(), ^{
//                 [self getIRCode];
//             });
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:7];
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_GET cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata){
            
            NSLog(@"getWindStatus-tcp:%@",jsondata);
            
            if(!jsondata || ![jsondata isKindOfClass:[NSDictionary class]]) return;
          
            if(![jsondata[@"state"] isKindOfClass:[NSNumber class]])
            {
                if ([jsondata[@"state"] isEqualToString:@"Success"])
                {
                    NSInteger windirValue = [jsondata[@"state"] intValue];
                    
                    btn_switcher.selected = !(windirValue==0);
                    //保存风向状态
                    if (windirValue == 0)
                    {
                        btn_switcher.selected = NO;
                        windInt = 0;
                    }
                    else
                    {
                        btn_switcher.selected = YES;
                        windInt = 1;
                    }
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self getIRCode];
                    });
                }
            }
        }];
    }
}

//get 获取当前的 IR Code 设定
- (void)getIRCode
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *ipUrlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=0&Get=%d",ipUrl,self.zIDStr,8];
        [Utitlity commonHTTPMethod:ipUrlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"getIRCode:%@",responseObject);
            
            if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            NSString *result = [responseObject objectForKey:@"state"];
            if(![result isKindOfClass:[NSNumber class]])
            {
                if ([responseObject[@"state"] isEqualToString:@"Success"])
                {
                    NSDictionary *item = responseObject[@"data"];
                    NSString *string = [NSString stringWithFormat:@"%@",item[@"Value"]];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.IRBtn setTitle:string forState:UIControlStateNormal];
                    });
                    
                    userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:string forKey:@"ir"];
                }
//                else
//                {
//                    [self getIRCode];
//                }

            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevThermostatGetCmd cmd = [self getWisDevThermostatGetCmdData:8];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_GET cmdLength:sizeof(WisDevThermostatGetCmd) withData:&cmd callRecivedBlock:^(id jsondata)
         {
             NSLog(@"getIRCode-tcp:%@",jsondata);
             
             if (!jsondata || ![jsondata isKindOfClass:[NSDictionary class]]) return;
             
             if(![jsondata[@"state"] isKindOfClass:[NSNumber class]])
             {
//                 int state = [jsondata[@"state"] intValue];
                 
                 if([jsondata[@"state"] isEqualToString:@"Success"])
                 {
                     NSDictionary *item = jsondata[@"data"];
                     NSString *string = [NSString stringWithFormat:@"%@",item[@"Value"]];
                     
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [self.IRBtn setTitle:string forState:UIControlStateNormal];
                     });
                     userDefaults = [NSUserDefaults standardUserDefaults];
                     [userDefaults setObject:string forKey:@"ir"];
                 }
             }
        }];
    }
}
//get 获取当前的学习状态
- (void)getLearningStatus
{
//    NSDictionary *LearningStatusDic = [jsondataArray objectAtIndex:7];
//    NSDictionary *LearningDataDic = LearningStatusDic[@"data"];
}

#pragma mark - SetCmdData

- (WisDevThermostatSetCmd)getWisDevThermostatSetCmdData:(int)set_index value:(int)value
{
    
    WisDevThermostatSetCmd cmd;
    memset(&cmd, 0, sizeof(WisDevThermostatSetCmd));
    strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String]);
    strcpy(cmd.did, [self.zIDStr UTF8String]);
    cmd.set_index = set_index;
    cmd.value = value;
    return cmd;
}


-(IBAction)powerClicked:(id)sender
{
    if (mPower == 0)
    {
        airValue = 5;
    }
    else if (mPower == 1)
    {
        airValue = 0;
    }
    
    ipUrl = [Utitlity judgeipUrl];
    
    [activity startAnimating];
    if (ipUrl)
    {
        NSString *powerStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=1&Set=1&Value=%d&Unit=unit",ipUrl,self.zIDStr,airValue];
        [Utitlity commonHTTPMethod:powerStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"powerClicked:%@",responseObject);
            
            if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            [activity stopAnimating];

            NSString *state = [responseObject objectForKey:@"state"];
            
            if(![responseObject[@"state"] isKindOfClass:[NSNumber class]])
            {
                if ([state isEqualToString:@"Success"])
                {
                    btn_power.selected = !btn_power.selected;
                    
                    if (btn_power.selected)
                    {
                        mPower = 1;
                    }
                    else
                    {
                        mPower = 0;
                    }
                    
                    //更新当前空调状态
                    NSDictionary *airValueDic = [allAirModeArray objectAtIndex:airValue];
                    [btn_air_mode setTitle:airValueDic[@"label"] forState:UIControlStateNormal];
                    userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:airValueDic[@"label"] forKey:@"air"];
                }
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
         WisDevThermostatSetCmd cmd = [self getWisDevThermostatSetCmdData:1 value:airValue];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_SET cmdLength:sizeof(WisDevThermostatSetCmd) withData:&cmd callRecivedBlock:^(id xdata){
            
            [activity stopAnimating];
            NSLog(@"powerClicked-tcp:%@",xdata);
            
            if(!xdata || ![xdata isKindOfClass:[NSDictionary class]]) return;
            
            NSString *state = [xdata objectForKey:@"state"];
            
            if(![state isKindOfClass:[NSNumber class]])
            {
                if ([state isEqualToString:@"Success"])
                {
                    btn_power.selected = !btn_power.selected;
                    
                    if (btn_power.selected)
                    {
                        mPower = 1;
                    }
                    else
                    {
                        mPower = 0;
                    }
                }
                
                //更新当前空调状态
                NSDictionary *airValueDic = [allAirModeArray objectAtIndex:airValue];
                [btn_air_mode setTitle:airValueDic[@"label"] forState:UIControlStateNormal];
                userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:airValueDic[@"label"] forKey:@"air"];
            }
        }];
    }
}




-(IBAction)airModeClicked:(id)sender
{
    [self doChoose:100];
}

-(IBAction)fanModeClicked:(id)sender
{
    [self doChoose:200];
}

- (IBAction)tempSet:(id)sender{
    [self doChoose:300];
}

- (IBAction)irCode:(id)sender{
    [self doChoose:400];
}

-(IBAction)windDirClicked:(id)sender
{
    int value = btn_switcher.selected ? 0:1;
    
    ipUrl = [Utitlity judgeipUrl];
    [activity startAnimating];
    
    if (ipUrl)
    {
        NSString *windStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=1&Set=4&Value=%d&Unit=unit",ipUrl,self.zIDStr,value];
        
        [Utitlity commonHTTPMethod:windStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            
            NSLog(@"windDirClicked:%@",responseObject);
            
            if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            NSString *state = [responseObject objectForKey:@"state"];
            
            if(![state isKindOfClass:[NSNumber class]])
            {
                if ([state isEqualToString:@"Success"])
                {
//                    btn_switcher.selected = !btn_switcher.selected;
                    if (btn_switcher.selected)
                    {
                        btn_switcher.selected = NO;
                        windInt = 0;
                    }
                    else
                    {
                        btn_switcher.selected = YES;
                        windInt = 1;
                    }
                    
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    [user setObject:[NSString stringWithFormat:@"%d",windInt] forKey:@"windInt"];

                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevThermostatSetCmd cmd = [self getWisDevThermostatSetCmdData:4 value:value];
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_SET cmdLength:sizeof(WisDevThermostatSetCmd) withData:&cmd callRecivedBlock:^(id xdata){
            [activity stopAnimating];
            
            NSLog(@"windDirClicked-tcp:%@",xdata);
            
            if(!xdata || ![xdata isKindOfClass:[NSDictionary class]]) return;
            
            NSString *state = [xdata objectForKey:@"state"];
            
            if(![state isKindOfClass:[NSNumber class]])
            {
                if ([state isEqualToString:@"Success"])
                {
//                    btn_switcher.selected = !btn_switcher.selected;
                    if (btn_switcher.selected)
                    {
                        btn_switcher.selected = NO;
                        windInt = 0;
                    }
                    else
                    {
                        btn_switcher.selected = YES;
                        windInt = 1;
                    }
                    
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    [user setObject:[NSString stringWithFormat:@"%d",windInt] forKey:@"windInt"];
                }
            }
        }];
    }
}

- (void)detectIntervalToSendTempSetCMD
{
}

-(void)setTemp:(int)tp
{
    [activity startAnimating];
    
    ipUrl = [Utitlity judgeipUrl];

    if (ipUrl)
    {
        NSString *tempStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=1&Set=3&Value=%d&Unit=C",ipUrl,self.zIDStr,tp];
        
        [Utitlity commonHTTPMethod:tempStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [activity stopAnimating];
            
            NSLog(@"setTemp:%@",responseObject);
            
            if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            NSString *state = [responseObject objectForKey:@"state"];
            if(![state isKindOfClass:[NSNumber class]])
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (![state isEqualToString:@"Success"])
                    {
                        [btn_set_temp setTitle:[NSString stringWithFormat:@"%d",temp] forState:UIControlStateNormal];
                        btn_set_temp.titleLabel.text = [NSString stringWithFormat:@"%d",temp];
                    }
                    else
                    {
                        temp = tp;
                        [btn_set_temp setTitle:[NSString stringWithFormat:@"%d",temp] forState:UIControlStateNormal];
                        btn_set_temp.titleLabel.text = [NSString stringWithFormat:@"%d",temp];
                        
                        //baocun
                        userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:[NSString stringWithFormat:@"%d",temp] forKey:@"set"];
                        
                    }
                });
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevThermostatSetCmd cmd = [self getWisDevThermostatSetCmdData:3 value:tp];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_SET cmdLength:sizeof(WisDevThermostatSetCmd) withData:&cmd callRecivedBlock:^(id xdata){
            
            [activity stopAnimating];
            
            NSLog(@"setTemp-tcp:%@",xdata);
            
            if(!xdata || ![xdata isKindOfClass:[NSDictionary class]]) return;
            NSString *state = [xdata objectForKey:@"state"];
            
            if(![state isKindOfClass:[NSNumber class]])
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (![state isEqualToString:@"Success"])
                    {
                        [btn_set_temp setTitle:[NSString stringWithFormat:@"%d",temp] forState:UIControlStateNormal];
                        btn_set_temp.titleLabel.text = [NSString stringWithFormat:@"%d",temp];
                    }
                    else
                    {
                        temp = tp;
                        [btn_set_temp setTitle:[NSString stringWithFormat:@"%d",temp] forState:UIControlStateNormal];
                        btn_set_temp.titleLabel.text = [NSString stringWithFormat:@"%d",temp];
                        
                        //baocun
                        userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:[NSString stringWithFormat:@"%d",temp] forKey:@"set"];
                    }
                });
            }
        }];
    }
}


-(IBAction)tempAddClicked:(id)sender
{
    [self setTemp:(temp+1)];
}

-(IBAction)tempSubClicked:(id)sender
{
    [self setTemp:(temp-1)];
}


//========================================================PickerView========================================


-(void)changeAirMode:(int)lastMode
{
    ipUrl = [Utitlity judgeipUrl];
    
     NSDictionary *item = [allAirModeArray objectAtIndex:lastMode];
    
    NSLog(@"airmode item:%@",item);
    
    if (ipUrl)
    {
        NSString *airStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=1&Set=1&Value=%d&Unit=unit",ipUrl,self.zIDStr,[item[@"value"] intValue]];
        
        [Utitlity commonHTTPMethod:airStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSLog(@"changeAirMode:%@",responseObject);
             
            if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             
             [activity stopAnimating];
             
             NSString *result = [responseObject objectForKey:@"state"];
             if(![result isKindOfClass:[NSNumber class]])
             {
                 if ([result isEqualToString:@"Success"])
                 {
                     [btn_air_mode setTitle:item[@"label"] forState:UIControlStateNormal];
                     btn_air_mode.titleLabel.text = item[@"label"];
                     
                     //baocun
                     userDefaults = [NSUserDefaults standardUserDefaults];
                     [userDefaults setObject:item[@"label"] forKey:@"air"];
                     
                     //power按钮状态
                     if ([item[@"value"] intValue] == 0)
                     {
                         NSLog(@"当前模式为off");
                         btn_power.selected = NO;
                     }else
                     {
                         btn_power.selected = YES;
                     }
                 }
                 else
                 {
                     NSDictionary *fDic = [allAirModeArray objectAtIndex:airValue];
                     [btn_air_mode setTitle:fDic[@"label"] forState:UIControlStateNormal];
                     btn_air_mode.titleLabel.text = fDic[@"label"];
                 }
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"error:%@",error);
         }];
    }
    else
    {
        WisDevThermostatSetCmd cmd = [self getWisDevThermostatSetCmdData:1 value:[item[@"value"] intValue]];
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_SET cmdLength:sizeof(WisDevThermostatSetCmd) withData:&cmd callRecivedBlock:^(id xdata){
            
            NSLog(@"changeAirMode-tcp:%@",xdata);
            
           if(!xdata || ![xdata isKindOfClass:[NSDictionary class]]) return;
            [activity stopAnimating];
            
            NSString *result = [xdata objectForKey:@"state"];
            if(![result isKindOfClass:[NSNumber class]])
            {
                if ([result isEqualToString:@"Success"])
                {
                    [btn_air_mode setTitle:item[@"label"] forState:UIControlStateNormal];
                    btn_air_mode.titleLabel.text = item[@"label"];
                    
                    //baocun
                    userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:item[@"label"] forKey:@"air"];
                    
                    //power按钮状态
                    if ([item[@"value"] intValue] == 0)
                    {
                        btn_power.selected = NO;
                    }else
                    {
                        btn_power.selected = YES;
                    }

                }
                else
                {
                    
                    NSDictionary *fDic = [allAirModeArray objectAtIndex:airValue];
                    [btn_air_mode setTitle:fDic[@"label"] forState:UIControlStateNormal];
                    btn_air_mode.titleLabel.text = fDic[@"label"];
                }
            }
        }];
    }
}

-(void)changeFanMode:(int)lastMode
{
    ipUrl = [Utitlity judgeipUrl];
    
    NSDictionary *item = [allFanModeArray objectAtIndex:lastMode];
    
    NSLog(@"fanmode item:%@",item);
    
    if (ipUrl)
    {
        NSString *fanStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=1&Set=2&Value=%d&Unit=unit",ipUrl,self.zIDStr,[item[@"value"] intValue]];
        
        [Utitlity commonHTTPMethod:fanStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            
            NSLog(@"changeFanMode:%@",responseObject);
            
            if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            NSString *result = [responseObject objectForKey:@"state"];
            
            if(![result isKindOfClass:[NSNumber class]])
            {
                if ([result isEqualToString:@"Success"])
                {
                    [btn_fan_mode setTitle:item[@"label"] forState:UIControlStateNormal];
                    
                    userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:item[@"label"] forKey:@"fan"];
                   
                }
                else
                {
                    NSDictionary *fanValueDic = [allFanModeArray objectAtIndex:fanValue];
                    [btn_fan_mode setTitle:fanValueDic[@"label"] forState:UIControlStateNormal];
                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevThermostatSetCmd cmd = [self getWisDevThermostatSetCmdData:2 value:[item[@"value"] intValue]];
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_SET cmdLength:sizeof(WisDevThermostatSetCmd) withData:&cmd callRecivedBlock:^(id xdata){
            
            NSLog(@"changeFanMode-tcp:%@",xdata);
            
            [activity stopAnimating];
            
           if(!xdata || ![xdata isKindOfClass:[NSDictionary class]]) return;
            
            NSString *result = [xdata objectForKey:@"state"];
            
            if(![result isKindOfClass:[NSNumber class]])
            {
                if ([result isEqualToString:@"Success"])
                {
                    [btn_fan_mode setTitle:item[@"label"] forState:UIControlStateNormal];
                    
                    //baocun
                    userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:item[@"label"] forKey:@"fan"];

                }
                else
                {
                    NSDictionary *fanValueDic = [allFanModeArray objectAtIndex:fanValue];
                    [btn_fan_mode setTitle:fanValueDic[@"label"] forState:UIControlStateNormal];
                }
            }
        }];
    }
    
}

- (void)setIRCode:(int)code
{
    ipUrl = [Utitlity judgeipUrl];
    
    if(ipUrl)
    {
        NSString *irStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Thermostat.cgi?ZID=%@&GET_SET=1&Set=5&Value=%d&Unit=unit",ipUrl,self.zIDStr,code];
        
        [Utitlity commonHTTPMethod:irStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"setIRCode:%@",responseObject);
            
            if(!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
             NSString *result = [responseObject objectForKey:@"state"];
            
            if(![result isKindOfClass:[NSNumber class]])
            {
                 if ([result isEqualToString:@"Success"])
                 {
                     [self.IRBtn setTitle:[NSString stringWithFormat:@"%d",code] forState:UIControlStateNormal];
                     
                     userDefaults = [NSUserDefaults standardUserDefaults];
                     [userDefaults setObject:[NSString stringWithFormat:@"%d",code] forKey:@"ir"];
                 }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevThermostatSetCmd cmd = [self getWisDevThermostatSetCmdData:5 value:code];
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_THERMOSTAT_SET cmdLength:sizeof(WisDevThermostatSetCmd) withData:&cmd callRecivedBlock:^(id xdata){
            NSLog(@"setIRCode-tcp:%@",xdata);
            
            if(!xdata || ![xdata isKindOfClass:[NSDictionary class]]) return;
            NSString *result = [xdata objectForKey:@"state"];
            
            if(![result isKindOfClass:[NSNumber class]])
            {
                if ([result isEqualToString:@"Success"])
                {
                    [self.IRBtn setTitle:[NSString stringWithFormat:@"%d",code] forState:UIControlStateNormal];
                    
                    userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:[NSString stringWithFormat:@"%d",code] forKey:@"ir"];
                }
            }
        }];
    }
}

- (void)updateDevStatusChangeData:(NSNotification *)data
{
    NSArray *updateList = [data.userInfo objectForKey:NOTIFICATION_USERINFO_UPDATEDATA];
    NSLog(@"remoteupdateList:%@",updateList);
    
//    if (updateList)
//    {
//         for (NSDictionary *item in updateList)
//         {
//             NSString *zid = [[item objectForKey:@"ZID"] lowercaseString];
//             NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
//             if ( deviceType == 6 && [zid isEqualToString:self.zIDStr])
//             {
//                 
//             }
//         }
//    }
}

-(void)doChoose:(int)tag
{
    UIPickerView *picker;
    int index = 0;
    if (tag == 100)
    {
        picker = pickerView_air;
        index = picker_air_index;
    }
    else if (tag == 200)
    {
        picker = pickerView_fan;
        index = picker_fan_index;
    }else if(tag == 300)
    {
        picker = pickerTemp;
        index = pickerIndex;
    }else
    {
        picker = IRPicker;
        index = IRIndex;
    }

    [picker selectRow:index inComponent:0 animated:NO];
    
    //ios 7 的自定义UIActionSheet
    if ([[UIDevice currentDevice].systemVersion floatValue] < 8)
    {
        self.actionPicker = [[ActionPicker alloc]initWithTitle:@"" delegate:self picker:picker];
        actionPicker.tag = tag;
        [actionPicker showInView:self.view.superview];
    }
    else
    {
        [self alertWithPicer:picker];
    }
	
	
}

-(void)didOKButtonPressed:(ActionPicker *)picker
{
    if (picker.tag == 100)
    {
//        int last_picker_air_index = picker_air_index;
        picker_air_index= [pickerView_air selectedRowInComponent:0];
        NSDictionary*item = [allAirModeArray objectAtIndex:picker_air_index];
        select_air = [[item objectForKey:@"value"]intValue];
        [btn_air_mode setTitle:item[@"label"] forState:UIControlStateNormal];
        [self changeAirMode:picker_air_index];
    }
    else if(picker.tag == 200)
    {
//        int last_picker_fan_index = picker_fan_index;
        picker_fan_index = [pickerView_fan selectedRowInComponent:0];
        NSDictionary *item = [allFanModeArray objectAtIndex:picker_fan_index];
        select_fan = [[item objectForKey:@"value"]intValue];
        [btn_fan_mode setTitle:[item objectForKey:@"label"] forState:UIControlStateNormal];
        [self changeFanMode:picker_fan_index];
    }
    else if(picker.tag == 300)
    {
        pickerIndex = [pickerTemp selectedRowInComponent:0];
        [self setTemp:[[tempArray objectAtIndex:pickerIndex] intValue]];
    }
    else if(picker.tag == 400)
    {
        IRIndex= [IRPicker selectedRowInComponent:0];
        [self setIRCode:[[IRArray objectAtIndex:IRIndex] intValue]];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView1 numberOfRowsInComponent:(NSInteger)component;
{
    if (pickerView1.tag == 100)
    {
        return [airModeArray count];
    }
    else if(pickerView1.tag == 200)
    {
        return [fanModeArray count];
    }
    else if(pickerView1.tag == 300)
    {
        tempArray = [[NSArray alloc] initWithObjects:@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30",nil];
        return [tempArray count];
    }
    else if(pickerView1.tag == 400)
    {
        IRArray = [[NSMutableArray alloc] init];
        for (int i = 0 ; i < 256 ; i++)
        {
            NSString *temStr = [NSString stringWithFormat:@"%d",i];
            [IRArray addObject:temStr];
        }
        return [IRArray count];
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView1 titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView1.tag == 100)
    {
        return [airModeArray objectAtIndex:row];
    }
    else if(pickerView1.tag == 200)
    {
        return [fanModeArray objectAtIndex:row];
    }
    else if(pickerView1.tag == 300)
    {
        return [tempArray objectAtIndex:row];
    }
    else
    {
        return [IRArray objectAtIndex:row];
    }
}


//================================================================================================

#pragma mark - ios UIAlertController
- (void)alertWithPicer:(UIPickerView *)picker
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:@"\n\n\n\n\n\n\n\n\n\n\n"// change UIAlertController height
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    //Make a frame for the picker & then create the picker
    CGRect pickerFrame = CGRectMake(12, 12, 270, 250);
    picker.frame = pickerFrame;
    ios8Picker = picker;
    NSLog(@"%ld",(long)ios8Picker.tag);
    
    
    //set the pickers selection indicator to true so that the user will now which one that they are chosing
    [picker setShowsSelectionIndicator:YES];
    
    //Add the picker to the alert controller
    [alert.view addSubview:picker];
    
    //make the toolbar view
     UIToolbar *toolView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, alert.view.frame.size.width-16, kToolBarHeight)];
    toolView.backgroundColor = [UIColor blackColor]; //set it's background
    toolView.barStyle = UIBarStyleBlackTranslucent;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, kToolBarHeight)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    //    titleLabel.text = title;
    UIBarButtonItem *bbtTitle = [[UIBarButtonItem alloc] initWithCustomView:titleLabel];
    UIBarButtonItem *bbtSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *bbtOK = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(OKWithPicker)];
    bbtOK.width = 60.f;
    UIBarButtonItem *bbtCancel = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(CancleWithPicker)];
    bbtCancel.width = 60.f;
    toolView.items = [NSArray arrayWithObjects:bbtCancel,bbtSpace,bbtTitle,bbtSpace,bbtOK, nil];
    
    [alert.view addSubview:toolView];
    
    [self presentViewController:alert animated:NO completion:nil];
}

- (void)OKWithPicker
{
    if (ios8Picker.tag == 100)
    {
        //        int last_picker_air_index = picker_air_index;
        picker_air_index= [pickerView_air selectedRowInComponent:0];
        NSDictionary*item = [allAirModeArray objectAtIndex:picker_air_index];
        select_air = [[item objectForKey:@"value"]intValue];
        [btn_air_mode setTitle:item[@"label"] forState:UIControlStateNormal];
        [self changeAirMode:picker_air_index];
    }
    else if(ios8Picker.tag == 200)
    {
        //        int last_picker_fan_index = picker_fan_index;
        picker_fan_index = [pickerView_fan selectedRowInComponent:0];
        NSDictionary *item = [allFanModeArray objectAtIndex:picker_fan_index];
        select_fan = [[item objectForKey:@"value"]intValue];
        [btn_fan_mode setTitle:[item objectForKey:@"label"] forState:UIControlStateNormal];
        [self changeFanMode:picker_fan_index];
    }
    else if(ios8Picker.tag == 300)
    {
        pickerIndex = [pickerTemp selectedRowInComponent:0];
        [self setTemp:[[tempArray objectAtIndex:pickerIndex] intValue]];
    }
    else if(ios8Picker.tag == 400)
    {
        IRIndex= [IRPicker selectedRowInComponent:0];
        [self setIRCode:[[IRArray objectAtIndex:IRIndex] intValue]];
    }

    [self dismissModalViewControllerAnimated:YES];
}

- (void)CancleWithPicker
{
    [self dismissModalViewControllerAnimated:YES];
}


@end
